package com.act;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.UserInfo;
import com.common.Constant;
import com.common.LocalFileHelper;
import com.common.TextHttpResponseHandler;
import com.control.UserControl;
import com.xike.kyt.R;
import com.mUI.MyProgressDialog;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class UserInfoAct extends BaseAct implements OnClickListener {

	private static final int REQUEST_CODE_TO_LOGIN = 5;
	private static final int REQUEST_CODE_TO_BIND_MOBILE = 6;

	LinearLayout layout_questions, layout_answers;
	TextView tv_back, tv_userName, tv_questionNum, tv_answerNum, tv_certifyInfo, tv_summary;
	ImageView img_avator;
	Button btn_focus;
	Button btn_addOrSend;
	Button btn_call;

	UserInfo userInfo;
	boolean isMine = false;

	long userId;

	BitmapDrawable defualtBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_userinfo);
		initViews();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey("userId")) {
				userId = bundle.getLong("userId");
				if (userId == UserControl.getLoginUserId()) {
					isMine = true;
				}
				serviceGetUserInfo(userId);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_LOGIN && resultCode > 0) {
			serviceGetUserInfo(userId);
		} else if (requestCode == REQUEST_CODE_TO_BIND_MOBILE && resultCode > 0) {
			// serviceGetUserInfo(userId);
			// 跳转到拨打电话
			// Intent it_call = new Intent
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void initViews() {
		defualtBitmap = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);

		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);

		layout_questions = (LinearLayout) findViewById(R.id.userinfo_layout_questions);
		layout_answers = (LinearLayout) findViewById(R.id.userinfo_layout_answerNums);
		layout_questions.setOnClickListener(this);
		layout_answers.setOnClickListener(this);

		tv_answerNum = (TextView) findViewById(R.id.userinfo_tv_answerNum);
		tv_certifyInfo = (TextView) findViewById(R.id.userinfo_tv_certifyInfo);
		tv_summary = (TextView) findViewById(R.id.userinfo_tv_summary);
		tv_userName = (TextView) findViewById(R.id.userinfo_tv_name);
		tv_questionNum = (TextView) findViewById(R.id.userinfo_tv_questionNum);

		img_avator = (ImageView) findViewById(R.id.userinfo_img_avator);
		img_avator.setImageBitmap(MyUtil.getRoundedCornerBitmap(defualtBitmap.getBitmap()));

		tv_back.setOnClickListener(this);

		btn_focus = (Button) findViewById(R.id.userinfo_btn_focus);
		btn_focus.setOnClickListener(this);
		btn_addOrSend = (Button) findViewById(R.id.userinfo_btn_addOrSend);
		btn_addOrSend.setOnClickListener(this);

		btn_call = (Button) findViewById(R.id.userinfo_btn_call);

	}

	@Override
	protected void updateViews() {

		MyUtil.setTextViewText(tv_userName, userInfo.getShow_name(), View.INVISIBLE, "");
		MyUtil.setTextViewText(tv_certifyInfo, userInfo.getInformation(), View.INVISIBLE, "无");
		MyUtil.setTextViewText(tv_summary, userInfo.getSummary(), View.INVISIBLE, "无");
		MyUtil.setTextViewText(tv_questionNum, String.valueOf(userInfo.getQuestion_nums()), 0, "0");
		MyUtil.setTextViewText(tv_answerNum, String.valueOf(userInfo.getAnswer_nums()), 0, "0");

		MyUtil.displayImageView(this, userInfo.getAvator(), img_avator, MyUtil.getRoundedCornerBitmap(defualtBitmap.getBitmap()), true);

		tv_questionNum.setOnClickListener(this);
		tv_answerNum.setOnClickListener(this);

		if (isMine) {
			btn_focus.setVisibility(View.GONE);
			btn_addOrSend.setVisibility(View.GONE);
			btn_call.setVisibility(View.GONE);

			tv_userName.setOnClickListener(this);
			img_avator.setOnClickListener(this);

		} else {
			btn_focus.setVisibility(View.VISIBLE);
			if (userInfo.isIs_focus()) {
				btn_focus.setText("已关注");
			}
			btn_focus.setOnClickListener(this);

			btn_addOrSend.setVisibility(View.VISIBLE);
			if (userInfo.isIs_friend()) {
				btn_addOrSend.setText("发送信息");
			} else {
				btn_addOrSend.setText("加为好友");
			}
			btn_addOrSend.setOnClickListener(this);

			btn_call.setVisibility(View.VISIBLE);
			btn_call.setOnClickListener(this);
		}
	}

	private void serviceGetUserInfo(long userId) {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("user_id", String.valueOf(userId)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_INFO, params);
		// 本地缓存
		if (LocalFileHelper.getInstance(this).fileIsExited(strUrl)) {
			UserInfo result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), UserInfo.class);
			dealRequestResult(result);
			return;
		}
		// 网络请求
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				UserInfo result = gson.fromJson(responseString, UserInfo.class);
				dealRequestResult(result);
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(UserInfoAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(UserInfo result) {
		MyProgressDialog.cancle();
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				userInfo = result;
				Log.e("dealRequestResult", "" + isMine);
				if (isMine) {
					UserControl.updateUserInfo(userInfo);
				}
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
		}
	}

	private void serviceFocusUser() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("user_id", String.valueOf(userInfo.getId())));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_FOCUS, params);
		// 网络请求
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null) {
					if (result.isReturnTrue()) {
						mToast.showToast(UserInfoAct.this, "关注成功");
						userInfo.setIs_focus(true);
						btn_focus.setText("已关注");
					} else {
						mToast.showToast(UserInfoAct.this, result.getError_description());
					}
				} else {
					mToast.showToast(UserInfoAct.this, getResources().getString(R.string.net_error));
				}

				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(UserInfoAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void serviceCancelFocusUser() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("user_id", String.valueOf(userInfo.getId())));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_CANCEL_FOCUS, params);
		// 网络请求
		client.delete(strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null) {
					if (result.isReturnTrue()) {
						mToast.showToast(UserInfoAct.this, "取消关注成功");
						userInfo.setIs_focus(false);
						btn_focus.setText("关注");
					} else {
						mToast.showToast(UserInfoAct.this, result.getError_description());
					}
				} else {
					mToast.showToast(UserInfoAct.this, getResources().getString(R.string.net_error));
				}

				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(UserInfoAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.userinfo_layout_answerNums:
			Intent it_answerList = new Intent(this, Answer_ListAct.class);
			it_answerList.putExtra("user_id", userInfo.getId());
			startActivity(it_answerList);
			break;
		case R.id.userinfo_layout_questions:
			Intent it_questionList = new Intent(this, Question_ListAct.class);
			it_questionList.putExtra("user_id", userInfo.getId());
			startActivity(it_questionList);
			break;
		case R.id.headTitle_tv_back:
			finish();
			break;
		case R.id.userinfo_btn_focus:
			if (UserControl.isLogined()) {
				if (userInfo.isIs_focus()) {
					serviceCancelFocusUser();
				} else {
					serviceFocusUser();
				}
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		case R.id.userinfo_btn_addOrSend:
			if (UserControl.isLogined()) {
				if (userInfo.isIs_friend()) {
					// 发送消息
					Intent it_toChat = new Intent(this, ChatAct.class);
					it_toChat.putExtra("userId", userInfo.getIm_username());
					it_toChat.putExtra("userName", userInfo.getShow_name());
					startActivity(it_toChat);
				} else {
					// 加为好友
					Intent it = new Intent(this, Friend_AddAct.class);
					it.putExtra("user_id", userId);
					startActivity(it);
				}
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;

		case R.id.userinfo_btn_call:
			if (UserControl.isLogined()) {
				if (UserControl.hasBindMobile()) {
					// 拨打电话页面
					String toUserMobile = userInfo.getMobile();
					if (StringUtil.isNotNull(toUserMobile)) {
						Intent it_call = new Intent(this, CallAct.class);
						it_call.putExtra("toUserName", userInfo.getShow_name());
						it_call.putExtra("toUserMobile", toUserMobile);
						it_call.putExtra("toUserId", userInfo.getId());

						startActivity(it_call);
					} else {
						mToast.showToast(UserInfoAct.this, "对方未绑定手机号");
					}

				} else {
					// 绑定手机号
					Intent it = new Intent(this, BindMobileAct.class);
					startActivityForResult(it, REQUEST_CODE_TO_BIND_MOBILE);
				}

			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;

		default:
			break;
		}
	}

}
